<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="100%" >
    <div>
      <Button type="primary" @click="startFn" style="margin-right: 5px">重置</Button>
      <Button type="primary" @click="resetFn" style="margin-right: 5px">刷新</Button>
      <Button type="primary" @click="testNextFn" style="margin-right: 5px">模拟切换</Button>
<!--      <Button type="primary" @click="joinFn">播放</Button>-->
    </div>
<!--    height:contentHeight*3+'px'-->
    <div ref="chartRef" :style="{width: contentWidth+'px',height:contentHeight*0.8+'px'}" ></div>

  </BasicDrawer>
</template>
<script lang="ts" setup>



import { BasicTable, useTable, TableAction } from '@/components/Table';
import {ref, computed, unref, h, toRaw, reactive, onMounted, nextTick, Ref} from 'vue';
import { Button,Card, Form, FormItem,} from 'ant-design-vue';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { useDrawer } from '@/components/Drawer';

import {

  t_user_0,
  t_user_1,t_user_2,t_user_3,t_user_4
} from './test.data';
import { BasicModal, useModalInner } from '@/components/Modal';
import * as echarts from 'echarts/core';
import {getPublishPaper,getPagerUserRanks,getPaperTeamRank,getUsers} from '@/api/heng/ex';
import { useECharts } from '@/hooks/web/useECharts';


import { useMessage } from "@/hooks/web/useMessage";
import util from '@/utils/util';

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const { createMessage } = useMessage();

const chooseQuestion = useDrawer();

const id = ref("")

const contentHeight = ref(window.innerHeight);
const contentWidth = ref(window.innerWidth);

const tableRef = ref();


const dataList = ref({});

const chartRef = ref<HTMLDivElement | null>(null);
const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

// 组件状态
const audio = ref(null);
const isPlaying=ref(false);
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //打开弹层后的回调
  // resetFields();
  setDrawerProps({ confirmLoading: false });
  // console.log("---data:",data)
  id.value = data.publishPaperId;
  // setDataFn();
  setDataFn2();
  // startFn();
  initAudio();
  // getUsers();
});

const getTitle = computed(() => ('查看个人排名'));


//async function handleSubmit()

async function handleSubmit() {
  try {

    closeDrawer();

  } catch (e) {
    console.log(e)
  } finally {
    setDrawerProps({ confirmLoading: false });

  }
}


function paperDetailFn(){
  setDrawerProps({ confirmLoading: true });

  getPublishPaper({publishPaperId:id.value}).then((res) => {
    if(res.code==200){
      let json=res.data;
      dataList.value = json;

    }else{
      createMessage.error(res.message);
    }
  }).finally(e=>{
    setDrawerProps({ confirmLoading: false });

  })




}

const count = ref(0);
const addNum = ref(0);

function handleClose(record: Recordable) {

  tableRef.value.remove(record);
  addNum.value = addNum.value - 1;
  countTableNum()
}


function countTableNum() {
  // let t_list = tableRef.value.getTableData();
  // console.log("----countTableNum:", t_list);

}

//获取当前阶段名称
function getModalName(){

}





/**
 * ------测试------
 */

const updateFrequency = 2000;//2000
const dimension = 0;
const countryColors = {
  '生产': '#7272d5',
  '研究院': '#c33d3d',
  '工业旅游及房地产': '#dcc630',
  'PMC': '#002a8f',
  '营销': '#003580',
  '品管': '#ed2939',
  '财务': '#e3821b',
  '设计': '#003897',
  '总经办': '#f93',
  '采购': '#bc002d',
  '东莞恒丽': '#024fa2',
  '仓储': '#2e658c',
  '人力后勤': '#00247d',
  '电商': '#63b349',
  '研发工程': '#8819c8',
  // Russia: '#d56a1e',
  // Turkey: '#e30a17',
  // 'United Kingdom': '#00247d',
  // 'United States': '#b22234'
};

var myChart;
var option ;
function setDataFn2(){
  // var chartDom = document.getElementById('main');
   myChart = echarts.init(chartRef.value);


  // console.log('----t_source:', t_source);
   option = {
    grid: {
      top: 10,
      bottom: 30,
      left: 150,
      right: 80
    },
    xAxis: {
      name:"分数",
      max: 'dataMax',
      axisLabel: {
        formatter: function (n) {
          // console.log("--x:",n)
          return Math.round(n) + '';
        }
      }
    },
    dataset: {
      source: []
    },
    yAxis: {
      name:"排行",
      type: 'category',
      inverse: true,
      max: 'dataMax',//'dataMax'
      axisLabel: {
        show: true,
        fontSize: 14,
        formatter: function (value) {//y 轴名字
          let v='';//v=value + '{flag|' + getFlag(value) + '}';
          v=value;
          // console.log("--v:",v)
          return v;
        },
        rich: {
          flag: {
            fontSize: 22,
            padding: 2
          }
        }
      },
      animationDuration: 300,
      animationDurationUpdate: 300
    },
    series: [
      {
        realtimeSort: true,
        seriesLayoutBy: 'column',
        type: 'bar',
        itemStyle: {
          //
          color: function (param) {
            return  countryColors[param.value[2]] ||'#5470c6';
          }
        },
        encode: {
          x: dimension,
          y: 1
        },
        label: {
          show: true,
          precision: 1,
          position: 'right',
          valueAnimation: true,
          fontFamily: 'monospace'
        }
      }
    ],
    // Disable init animation.
    animationDuration: 0,
    animationDurationUpdate: updateFrequency,
    animationEasing: 'linear',
    animationEasingUpdate: 'linear',
    graphic: {
      elements: [
        {
          type: 'text',
          right: 160,
          bottom: 60,
          style: {
            text: "",
            font: 'bolder 80px monospace',
            fill: 'rgba(100, 100, 100, 0.25)'
          },
          z: 100
        }
      ]
    }
  };
  // console.log(option);
  myChart.setOption(option);

}
function startFn(){
  // option.yAxis.data=userNames;
  // option.yAxis.max=userNames.length;
  test_start.value=0;
  option.series[0].data = t_user_0;
  // option.graphic.elements[0].style.text = "第1阶段";
  myChart.setOption(option);

}
function resetFn(){

  getPagerUserRanksFn();
  // paperDetailFn();
}
function joinFn(){
  // option.series[0].data = t_user_2;
  // option.graphic.elements[0].style.text = "第二阶段";
  // myChart.setOption(option);
  playAudio();
}

const test_start=ref(0);
//模拟切换
function testNextFn(){
  if(test_start.value<5){
    test_start.value=test_start.value+1;
    let arr=[];
    if(test_start.value==1){
      arr=t_user_1;
    }
    if(test_start.value==2){
      arr=t_user_2;
    }
    if(test_start.value==3){
      arr=t_user_3;
    }
    if(test_start.value==4){
      arr=t_user_4;
    }
    option.series[0].data = arr;
    myChart.setOption(option);

  }else{
    test_start.value=0;
  }


}


/**
 * 个人排名刷新
 */
function getPagerUserRanksFn() {
  let t={publishPaperId:id.value};
  // console.log("---getPagerUserRanksFn::",t)
  getPagerUserRanks(t).then((res) => {
    if(res.code==200){
      let arr=res.data;
      let tables=[];
      arr.forEach((item)=>{
        let arr2=[item.score,item.sort+""+item.userName,item.deptName];
        tables.push(arr2);
      })
      option.series[0].data = tables;
      // option.graphic.elements[0].style.text = "未开始";
      myChart.setOption(option);

    }else{
      createMessage.error(res.message);
    }
  }).finally(e=>{
    setDrawerProps({ confirmLoading: false });
    playAudio();
  })
}

// 初始化音频
const initAudio = () => {
  try {
    audio.value = new Audio("http://220.161.77.66:10111/app_file/mp3/sys/pass.mp3");
    // audio.value.loop = props.loop;
    // audio.value.volume = volume.value;

    // 监听音频事件
    audio.value.addEventListener('play', () => {
      isPlaying.value = true;
    });

    audio.value.addEventListener('pause', () => {
      isPlaying.value = false;
    });

    audio.value.addEventListener('ended', () => {
      isPlaying.value = false;
    });

    audio.value.addEventListener('error', (err) => {
      console.error('Audio error:', err);
    });

  } catch (err) {
    console.error('Failed to initialize audio:', err);
  }
};

// 播放音频
const playAudio = async () => {
  if (!audio.value) return;

  try {
    // 尝试播放
    await audio.value.play();
    isPlaying.value = true;
  } catch (err) {
    console.error('Failed to play audio:', err);

  }
};

</script>
<style lang="less">
.item-row {
  margin: 0 auto;

  //padding-left: 5%;
  .ant-form-item-label {
    flex: 0 0 28.5%;
    max-width: 28.5%;
  }
}

.lqfp-8 {
  //padding-left: 9% !important;

}
</style>

